import json
import pprint
import base64
from flask import Flask, request, render_template, send_from_directory, jsonify
from flask_cors import CORS
import os
from datetime import date

app = Flask(__name__)
CORS(app, resources=r'/*')  # 注册CORS, "/*" 允许访问所有api


@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'),
                               'favicon.ico', mimetype='image/vnd.microsoft.icon')


@app.route('/', methods=['GET', 'POST'])
def form_info():
    # 如果是get请求就返回页面
    if request.method == 'GET':
        return render_template('index.html')
    else:
        num = request.form['num']
        name = request.form['name']
        date = request.form['nowdate']
        # date = str(date.date())
        # 创建文件夹
        if not os.path.exists(date):  # 判断当前路径是否存在，没有则创建new文件夹
            os.makedirs(date)
        file_name = str(num) + '-' + str(name) + '-' + date

        # print(request.form)
        pic = request.files.get('pic')
        if pic is None:
            return '<p style="color:red;font-size:60px;text-align:center;margin:50vh auto;">很抱歉,提交失败！</p>'
        suffix = pic.filename.rsplit('.', 1)[-1]
        pic.save(f'./{date}//{file_name}.{suffix}')
        # pic_location = f'/{date}/{file_name}.{suffix}'
        # return f' <p style="color:#47ea55;font-size:70px;text-align:center;margin:50vh auto;margin-bottom:20px;">提交成功<br/><span style="font-size:40px;">{file_name}</span></p>'
        return render_template('succ.html', picContent=file_name)



@app.route('/info', methods=['POST'])
def getInfo():
    # # data = request.get_data()
    # # data = json.loads()
    # name=request.form.get('name')
    # num = request.form.get('num')
    # subDate = request.form.get('dd')
    # pic = request.form.get('pic')
    # num=data['num']
    # date = data['dd']
    # pic = data['pic']['content']
    # pprint.pprint(request.form)

    # temp = base64.b64decode(pic)
    # pprint.pprint(request.files['pic'])
    # with open("a.jpg", "wb") as fp:
    #     fp.write(request.files.get('pic'))

    # json_data = request.get_data()
    # print(type(pic))
    # byt = base64.b64encode(bytes(pic,'utf-8'))
    # try:
    #     with open('001.jpg', 'wb') as f:
    #         f.write(byt)
    # except Exception as e:
    #     print(e)


    
    # print(imagedata)
    # file = open('1.png', "wb")
    # file.write(imagedata)
    # file.close()
    
    
    # file_name = str(num) + '-' + str(name) + '-' + date
    # try:
    #     pic = request.form.get('pic')
    #     imgSrc =  pic.split(',')[1]
    #     imagedata = base64.b64decode(imgSrc)
    #     imagedata.save(f'./{date}//{file_name}.jpg')
    try:
        name = request.form['name']
        num = request.form['num']
        date = request.form['date']
        pic = request.form['pic']
        print(name,num,date)
        # base64图片解码并保存，需要注意的是base64数据前面的内容不需要
        imgSrc =  pic.split(',')[1]
        imagedata = base64.b64decode(imgSrc)
        if not os.path.exists(date):  # 判断当前路径是否存在，没有则创建new文件夹
            os.makedirs(date)
        file_name= f"{num}-{name}-{date}"
        with open(f'{date}//{file_name}.jpg','wb') as f:
            f.write(imagedata)
        return jsonify({'status': True,
                'filesave':file_name})
    except Exception as e:
        print(e)
        return jsonify({
            'status':False
        })
    


if __name__ == '__main__':
    app.run(debug=True,
            port=8084
            )
